var app = getApp();
Page({
  data: {
    buttonBounding: app.globalData.buttonBounding,
    baseInfo: {},
    list: [],
    phone: "",
    stars: [] // 星空动画数据
  },
  onLoad: function () {
    this.initStars();
  },
  onShow() {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    console.log('prevPage.data.list', prevPage.data.list)
    this.setData({ 
      list: prevPage.data.list, 
      phone: prevPage.data.keyWord 
    });
    // 重新初始化星空动画
    this.initStars();
  },
  // 初始化星空背景
  initStars() {
    const stars = [];
    for (let i = 0; i < 50; i++) {
      stars.push({
        left: Math.random() * 100,
        top: Math.random() * 100,
        size: Math.random() * 6 + 2,
        delay: Math.random() * 3
      });
    }
    this.setData({ stars });
  },
  // 图片加载成功处理
  onImageLoad(e) {
    const index = e.currentTarget.dataset.index;
    const list = this.data.list;
    list[index].imageLoaded = true;
    list[index].imageError = false;
    this.setData({ list });
  },
  // 图片加载错误处理
  onImageError(e) {
    const index = e.currentTarget.dataset.index;
    const list = this.data.list;
    list[index].imageError = true;
    list[index].imageLoaded = false;
    this.setData({ list });
  },
  // 返回上一页
  goBack() {
    // 添加触觉反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({
        type: 'light'
      });
    }
    wx.navigateBack();
  },
  goResult(e) {
    // 添加触觉反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({
        type: 'medium'
      });
    }
    const index = e.currentTarget.dataset.index;
    const selectedItem = this.data.list[index];
    
    // 获取质保ID
    const warrantyId = selectedItem.warrantyId || selectedItem.id;
    
    if (warrantyId) {
      // 使用质保ID跳转到结果页面
      wx.navigateTo({ 
        url: `/pages/warranty/result/index?warrantyId=${warrantyId}`,
        success: () => {
          console.log('导航成功, warrantyId:', warrantyId);
        },
        fail: (err) => {
          console.error('导航失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    } else {
      console.error('质保数据中缺少ID字段:', selectedItem);
      wx.showToast({
        title: '数据异常，请联系客服',
        icon: 'none',
        duration: 2000
      });
    }
  },
  // 页面分享
  onShareAppMessage() {
    return {
      title: 'KSG质保查询 - 专业汽车膜产品质保服务',
      path: '/pages/warranty/query/index',
      imageUrl: '/images/share-bg.jpg'
    };
  },
  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: 'KSG质保查询 - 专业汽车膜产品质保服务',
      query: '',
      imageUrl: '/images/share-bg.jpg'
    };
  }
});
